package com.yanggu.bigdata.realtime.utils

import cn.hutool.core.bean.BeanUtil
import com.alibaba.fastjson.JSONObject
import com.yanggu.bigdata.realtime.common.GmallConfig

import java.sql.{Connection, DriverManager, PreparedStatement, ResultSet}
import java.util
import java.util.Properties

/**
 * Phoenix工具类, 封装phoenix的查询代码
 */
object PhoenixUtil {

  //初始化链接, 同时使用懒加载的方式
  private lazy val connection: Connection = {
    Class.forName(GmallConfig.PHOENIX_DRIVER)
    val properties = new Properties
    //phoenix查询时需要设置这个参数
    properties.setProperty("phoenix.schema.isNamespaceMappingEnabled", "true")
    val tempConnection = DriverManager.getConnection(GmallConfig.PHOENIX_SERVER, properties)
    //设置库名
    tempConnection.setSchema(GmallConfig.HBASE_SCHEMA)
    tempConnection
  }

  /**
   * 使用sql查询数据
   *
   * @param sql sql是完整的sql
   * @param clazz
   * @tparam T 泛型类
   * @return
   */
  def queryList[T](sql: String, clazz: Class[T]) = {
    var statement: PreparedStatement = null
    var resultSet: ResultSet = null
    try {
      statement = connection.prepareStatement(sql)
      resultSet = statement.executeQuery
      val list = new util.ArrayList[T]
      val metaData = resultSet.getMetaData
      val count = metaData.getColumnCount
      while (resultSet.next()) {
        val data = clazz.newInstance
        //循环为字段赋值, 将字段的值赋值到对象的成员变量中
        for (columnIndex <- 1 to count) {
          BeanUtil.setFieldValue(data, metaData.getColumnName(columnIndex), resultSet.getObject(columnIndex))
        }
        list.add(data)
      }
      list
    } catch {
      case e: Exception =>
        e.printStackTrace()
        throw new RuntimeException(s"查询维度信息失败, 对应的sql: $sql")
    } finally {
      if (resultSet != null) {
        resultSet.close()
      }
      if (statement != null) {
        statement.close()
      }
    }
  }

  //使用main方法进行测试
  def main(args: Array[String]): Unit = {
    val sql = "SELECT * from BASE_TRADEMARK"
    val list = queryList[JSONObject](sql, classOf[JSONObject])
    list.forEach(println(_))
  }

}
